package com.jinyang.web

import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.graphics.Bitmap
import android.graphics.PixelFormat
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import android.webkit.WebSettings
import android.widget.RelativeLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.github.lzyzsd.jsbridge.CallBackFunction
import com.github.lzyzsd.jsbridge.DefaultHandler
import com.jinyang.baserouter.PATH_ACTIVITY_WEB
import com.jinyang.baserouter.log
import com.jinyang.web.databinding.ActivityWebBinding
import com.jinyang.web.webview.BridgeHelper
import com.jinyang.web.webview.X5JsBridgeWebView
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient
import com.tencent.smtt.export.external.interfaces.SslError
import com.tencent.smtt.export.external.interfaces.SslErrorHandler
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebView
import org.json.JSONException
import org.json.JSONObject

//一旦主动指定分组之后，应用内路由需要使用 ARouter.getInstance().build(path, group) 进行跳转，手动指定分组，否则无法找到
@Route(path = PATH_ACTIVITY_WEB, group = "web1")
class WebActivity : AppCompatActivity() {
    private lateinit var binding: ActivityWebBinding

    @Autowired
    lateinit var url: String
    private var receiveError = false
    var mCustomView: View? = null
    private var mCustomViewCallback: IX5WebChromeClient.CustomViewCallback? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ARouter.getInstance().inject(this)
        binding =
            DataBindingUtil.setContentView(this, R.layout.activity_web)
        initWebView()
        url?.let { binding.webView.loadUrl(it) }
    }

    private fun initWebView() {
        window.setFormat(PixelFormat.TRANSLUCENT)
        binding.webView.view.overScrollMode = View.OVER_SCROLL_ALWAYS
        binding.webView.setDefaultHandler(DefaultHandler())
        binding.webView.setInitialScale(10)
        binding.webView.webChromeClient = mWebChromeClient
        //该方法解决的问题是打开浏览器不调用系统浏览器，直接用webview打开
        binding.webView.webViewClient = MyWebViewClient(binding.webView.bridgeHelper)
        binding.webView.settings.run {
            javaScriptEnabled = true
            //        从Android5.0开始，WebView默认不支持同时加载Https和Http混合模式。加上下面这句代码就好了：
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE
            }
            loadWithOverviewMode = true
            defaultTextEncodingName = "UTF-8"
            mediaPlaybackRequiresUserGesture = false
            useWideViewPort = true
            setSupportZoom(true)
            layoutAlgorithm = com.tencent.smtt.sdk.WebSettings.LayoutAlgorithm.SINGLE_COLUMN
            domStorageEnabled = true
            cacheMode = WebSettings.LOAD_NO_CACHE
            // 设置可以访问文件
            allowFileAccess = true
        }

        //兼容视频
        setWebViewExtension(1)

//      注册监听方法当js中调用callHandler方法时会调用此方法（handlerName必须和js中相同）
        binding.webView.registerHandler("goBack") { data: String?, function: CallBackFunction? -> finish() }

    }

    private fun setWebViewExtension(i: Int) {
        try {
            if (binding.webView.x5WebViewExtension != null) {
                val data = Bundle()
                data.putBoolean("standardFullScreen", false)
                //true表示标准全屏，false表示X5全屏；不设置默认false，
                data.putBoolean("supportLiteWnd", false)
                //false：关闭小窗；true：开启小窗；不设置默认true，
                data.putInt("DefaultVideoScreen", i)
                //1：以页面内开始播放，2：以全屏开始播放；不设置默认：1
                binding.webView.x5WebViewExtension.invokeMiscMethod("setVideoParams", data)
                binding.webView.x5WebViewExtension.setScrollBarFadingEnabled(false) //去除滚动条
            }
        } catch (ex: Exception) {
            ex.printStackTrace()
        }
    }


    override fun onConfigurationChanged(config: Configuration) {
        super.onConfigurationChanged(config)
        log("webAct:onConfigurationChanged:" + config.orientation)
        when (config.orientation) {
            Configuration.ORIENTATION_LANDSCAPE -> {
                window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN)
                window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
                val lp = RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.MATCH_PARENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT
                )
                lp.setMargins(0, 0, 0, 0)
            }
            Configuration.ORIENTATION_PORTRAIT -> {
                window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
                window.addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN)
                val lp2 = RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.MATCH_PARENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT
                )
                lp2.setMargins(0, 50, 0, 0)
            }
            else -> {}
        }
    }

    /**
     * 全屏时按返加键执行退出全屏方法
     */
    fun hideCustomView() {
        log("webAct:hideCustomView")
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        mWebChromeClient.onHideCustomView()
    }

    /**
     * 判断是否是全屏
     */
    fun inCustomView(): Boolean {
        return mCustomView != null
    }

    private fun goBack() {
        log("webAct:inCustomView=" + inCustomView())
        if (inCustomView()) {
            hideCustomView()
            binding.webView.reload()
            return
        }
        if (binding.webView.canGoBack()) {
            binding.webView.goBack()
        } else {
            finish()
        }
    }

    override fun onPause() {
        super.onPause()
        binding.webView.onPause()
    }

    override fun onResume() {
        super.onResume()
        binding.webView.onResume()
    }


    override fun onBackPressed() {
        goBack()
        super.onBackPressed()
    }

    public override fun onDestroy() {
        binding.webView.destroy()
        super.onDestroy()
    }

    private val mWebChromeClient = object : WebChromeClient() {
        override fun onProgressChanged(view: WebView, newProgress: Int) {
            if (newProgress == 100) {
                binding.webviewProgress.visibility = View.GONE
            } else {
                binding.webviewProgress.visibility = View.VISIBLE
                binding.webviewProgress.progress = newProgress //设置加载进度
            }
            super.onProgressChanged(view, newProgress)
        }

        override fun onReceivedTitle(view: WebView, title: String) {

        }

        override fun onShowCustomView(
            view: View,
            callback: IX5WebChromeClient.CustomViewCallback
        ) {
            log("webAct:onShowCustomView")
            super.onShowCustomView(view, callback)
            this@WebActivity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
            binding.webView.visibility = View.GONE
            // 如果一个视图已经存在，那么立刻终止并新建一个
            if (mCustomView != null) {
                callback.onCustomViewHidden()
                return
            }
            binding.frameLayout.addView(view)
            mCustomView = view
            mCustomView!!.visibility = View.VISIBLE
            mCustomViewCallback = callback
            binding.frameLayout.visibility = View.VISIBLE
            setWebViewExtension(2)
        }

        override fun onHideCustomView() {
            log("webAct:onHideCustomView")
            if (mCustomView == null) {
                // 不是全屏播放状态
                return
            }
            binding.webView.visibility = View.VISIBLE
            this@WebActivity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
            mCustomView!!.visibility = View.GONE
            binding.frameLayout.removeView(mCustomView)
            mCustomView = null
            binding.frameLayout.visibility = View.GONE
            mCustomViewCallback!!.onCustomViewHidden()
            setWebViewExtension(1)
        }
    }

    private open inner class MyWebViewClient(bridgeHelper: BridgeHelper?) :
        X5JsBridgeWebView.MyWebViewClient(bridgeHelper) {
        // webView默认是不处理https请求的，页面显示空白,
        // onReceivedSslError为webView处理ssl证书设置
        override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
            handler.proceed() //忽略 SSL 证书错误
            // handler.cancel();//挂起连接，为默认方式
            // handler.handleMessage(null);
        }

        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            try {
                if (url.startsWith("arouter:") || url.startsWith("tel:")
                    || url.startsWith("http://test.ljy.com")
                    || url.startsWith("https://test.ljy.com")
                ) {
                    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                    startActivity(intent)
                    return true
                }
            } catch (e: Exception) {
                return true
            }
            return super.shouldOverrideUrlLoading(view, url)
        }

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            super.onPageStarted(view, url, favicon)
            log("pageStart")
            receiveError = false
        }

        override fun onPageFinished(view: WebView?, url: String) {
            super.onPageFinished(view, url)
            if (receiveError) {
                binding.webView.visibility = View.GONE
                return
            }
            binding.webView.visibility = View.VISIBLE
            this@WebActivity.url = url
            log("onPageFinished_url:$url")

        }

        /**
         * 页面加载错误时执行的方法，但是在6.0以下，有时候会不执行这个方法
         */
        override fun onReceivedError(
            view: WebView?,
            errorCode: Int,
            description: String?,
            failingUrl: String?
        ) {
            super.onReceivedError(view, errorCode, description, failingUrl)
            log("onReceivedError: " + errorCode + "_" + description + "_" + failingUrl)
            if (errorCode == -1) {
                return
            }
            receiveError = true
        }
    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            goBack()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }


}

